package com.black.common.redis;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * @author linwenfeng
 */
public class ProtostuffRedisSerializer implements RedisSerializer<Object> {

    private static final Schema<ObjectWrapper> SCHEMA = RuntimeSchema.getSchema(ObjectWrapper.class);

    public ProtostuffRedisSerializer() {

    }

    @Override
    public byte[] serialize(Object object) {
        if (object == null) {
            return new byte[0];
        } else {
            LinkedBuffer buffer = LinkedBuffer.allocate(512);
            byte[] var3;
            try {
                var3 = ProtostuffIOUtil.toByteArray(new ObjectWrapper(object), SCHEMA, buffer);
            } finally {
                buffer.clear();
            }
            return var3;
        }
    }

    @Override
    public Object deserialize(byte[] bytes) {
        if (bytes != null && bytes.length != 0) {
            try {
                ObjectWrapper objectWrapper = new ObjectWrapper();
                ProtostuffIOUtil.mergeFrom(bytes, objectWrapper, SCHEMA);
                return objectWrapper.getObject();
            } catch (Exception var3) {
                throw new RuntimeException(var3.getMessage(), var3);
            }
        } else {
            return null;
        }
    }
}

